#include "stdafx.h"
#include "RenderbufferObject.h"
#include <iostream>
#include <Utilities\glext.h>
#include <Utilities\Extensions.h>

using namespace std;

RenderbufferObject::RenderbufferObject(void)
: _RBOObject(CreateBufferId())
{}

RenderbufferObject::RenderbufferObject(const GLenum internalFormat, const int width, const int height)
: _RBOObject(CreateBufferId())
{
	Set(internalFormat, width, height);
}

RenderbufferObject::~RenderbufferObject(void)
{
	glDeleteRenderbuffersEXT(1, &_RBOObject);
}

void RenderbufferObject::Bind(void)
{
	glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, _RBOObject);
}

void RenderbufferObject::Unbind(void)
{
	glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, 0);
}

void RenderbufferObject::Set(const GLenum internalFormat, const int width, const int height)
{
	int maxSize = RenderbufferObject::GetMaxSize();
	if (width > maxSize || height > maxSize)
	{
		cerr << "RenderbufferObject::RenderbufferObject() ERROR:\n\t" << "Size too big (" << width << ", " << height << ")\n";
		return;
	}

	// Guarded bind
	GLint savedId = 0;
	glGetIntegerv(GL_RENDERBUFFER_BINDING_EXT, &savedId);
	if (static_cast<GLuint>(savedId) != _RBOObject)
	{
		Bind();
	}

	// Allocate memory for renderBuffer
	glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, internalFormat, width, height);

	// Guarded unbind
	if (static_cast<GLuint>(savedId) != _RBOObject)
	{
		Unbind();
	}
}

const GLuint RenderbufferObject::GetId(void) const 
{
	return _RBOObject;
}

GLint RenderbufferObject::GetMaxSize(void)
{
	GLint maxAttach = 0;
	glGetIntegerv(GL_MAX_RENDERBUFFER_SIZE_EXT, &maxAttach);
	return maxAttach;
}

GLuint RenderbufferObject::CreateBufferId(void) 
{
	GLuint id = 0;
	glGenRenderbuffersEXT(1, &id);
	return id;
}

